using System;
using System.Collections;
using System.Web.UI.WebControls;
using PHSRAG.Insight21.CDS;
using PHSRAG.Insight21.Common.Pages;
using PHSRAG.Insight21.Policy;
using PHSRAG.Utility;

namespace PHSRAG.Insight21.Humans
{
    /// <summary>
    /// The ConsentFormSelectionPage allows a user to select from multiple
    /// consent forms if more than one is attached to a protocol.
    /// </summary>
    public partial class ConsentFormSelectionPage : BasePage
    {
        #region Constants

        private const string AttachmentType = "ATCHTYPE_CNSNTFRM";

        #endregion

        #region instance Variables

        private ICachePolicy _cachePolicy;
        private int _consentFormCount;
        private ICachePolicy _pageCachePolicy;
        private int _protocolId;

        #endregion

        #region Event Handlers

        /// <summary>
        /// Loads the grid with the consent forms associated with
        /// the protocol in the incoming hash.
        /// </summary>
        /// <param name="sender">sender of the event</param>
        /// <param name="e">arguments of the event</param>
        protected void OnPageLoad(object sender, EventArgs e)
        {
            annunciator.Title = string.Empty;
            annunciator.Message = string.Empty;
            Hashtable incomingPageHash = _cachePolicy.GetCachedObject(Keys.IncomingDataKey) as Hashtable;

            try
            {
                if (incomingPageHash != null)
                {
                    // Pull incoming data out of cache and store under the page's cache
                    _protocolId = Convert.ToInt32(incomingPageHash[Keys.ProtocolIdKey]);
                    _consentFormCount = Convert.ToInt32(incomingPageHash[Keys.ConsentCountKey]);
                }
                else
                {
                    throw new Exception("Not enough information is available to display this page.");
                }

                if (_consentFormCount > 1)
                {
                    consentLineUpGrid.PageSize = Settings.GetKeyValue("HumansDataGrid.ItemsPerPage", 20);
                    ArrayList consentList = Protocol.GetElectronicOnlyProtocolDocuments(_protocolId, AttachmentType, _cachePolicy);
                    //Remove the unpublished consent forms
                    for (int j = consentList.Count - 1; j >= 0; --j)
                    {
                        ProtocolDocument consentForm = (ProtocolDocument) consentList[j];
                        if (!consentForm.Published)
                        {
                            consentList.RemoveAt(j);
                        }
                    }
                    if (consentList.Count == 0)
                    {
                        consentPanel.Visible = false;
                    }
                    else
                    {
                        consentLineUpGrid.DataSource = consentList;
                        consentLineUpGrid.DataKeyField = "Id";
                        consentLineUpGrid.DataBind();
                        consentPanel.Visible = true;
                    }
                }
            }
            catch (Exception ex)
            {
                DisplayExceptionReport(ex);
            }
        }

        /// <summary>
        /// Handles events raised by clicking on items in the grid.  If the command associated
        /// with the event is "SelectConsent", data relevant to the details page is stored to
        /// session and the consent form launched.
        /// </summary>
        /// <param name="source">The object raising an event.</param>
        /// <param name="e">Argument associated with the event</param>
        private void OnItemCommand(object source, DataGridCommandEventArgs e)
        {
            try
            {
                if (e.CommandName == "SelectConsent")
                {
                    ProtocolDocument protocolDocument = new ProtocolDocument(_cachePolicy);
                    protocolDocument.Load(DataAccess.GetConnectionString(), (int) consentLineUpGrid.DataKeys[e.Item.ItemIndex]);
                    LaunchConsentForm(UIUtility.GetConsentFormWithFooter(_cachePolicy, protocolDocument));
                }
            }
            catch (Exception ex)
            {
                DisplayExceptionReport(ex);
            }
        }

        #endregion

        #region Web Form Designer generated code

        /// <summary>Initializes the page, sets up caching policies</summary>
        /// <param name="e">Arguments from the event</param>
        protected override void OnInit(EventArgs e)
        {
            InitializeComponent();
            base.OnInit(e);
            _cachePolicy = (Policy.ICachePolicy) Session[Policy.Names.CachePolicyKey];
            _pageCachePolicy = (Policy.ICachePolicy) Session[Policy.Names.PageCachePolicyKey];
        }

        /// <summary>
        /// Required method for Designer support - do not modify
        /// the contents of this method with the code editor.
        /// </summary>
        private void InitializeComponent()
        {
            this.Load += new System.EventHandler(this.OnPageLoad);
            this.consentLineUpGrid.ItemCommand += new DataGridCommandEventHandler(this.OnItemCommand);
        }

        #endregion

        #region private methods

        /// <summary>
        /// Displays an error message on the screen to the user with the exception, and all
        /// inner exception messages.
        /// </summary>
        /// <param name="ex">The exception to report on</param>
        private void DisplayExceptionReport(Exception ex)
        {
            annunciator.Title = InsightUtilities.Constants.Annunciator.Title;
            annunciator.Message = ExceptionReport.GetExceptionInfo(ex, false);
        }

        /// <summary>
        /// Launches the consent Form corresponding with the related document footer
        /// </summary>
        /// <param name="document">protocolDocument object</param>
        private void LaunchConsentForm(Document document)
        {
            Hashtable outgoingData = new Hashtable();
            outgoingData[Keys.DocumentKey] = document;
            _pageCachePolicy.Cache(Keys.IncomingDataKey, outgoingData);
            //Script for popup window
            string script = "\n<script language=JavaScript id='Display'>\n" +
                "window.close(); \n" +
                    "window.open('../Research/DownloadForm.aspx', 'ViewFile', 'resizable=yes, status=yes, toolbar=no, scrollbars=yes'); \n" +
                        "</script>";

            if (!Page.ClientScript.IsClientScriptBlockRegistered("Display"))
            {
                Page.ClientScript.RegisterClientScriptBlock(GetType(), "Display", script);
            }
        }

        #endregion
    }
}